package com.linkai.JUC._12_forkjoin;

import java.awt.*;
import java.util.concurrent.RecursiveTask;

/**
 * @Description: ForkJoin
 *                求和计算任务：小与临界值直接计算，大于临界值使用 ForkJoin 计算
 *                如何使用ForkJoin
 *                1. forkjoinpool 通过它来执行
 *                2. 计算任务 forkjoinPool.execute(ForkJoinTask task)
 *                3. 计算类要继承 ForkJoinTask
 *
 * @Author: 林凯
 * @Date: 2021/10/25 18:20
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;     // 1
    private Long end;       // 199999999

    // 临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {
    }

    // 计算方法：小与临界值时直接计算；大于临界值时使用 ForkJoin
    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum +=i;
            }
//            System.out.println(sum);
            return sum;
        } else {    // forkjoin 有点像递归
            long midle = (start + end) / 2;     // 中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, midle);
            task1.fork();       // 拆分任务，把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(midle + 1, end);
            task2.fork();

            return task1.join() + task2.join();
        }
    }
}
